import log from "./logger";
import {spawn} from "child_process";
import * as fs from "fs";
import settings from "./settings";

class PromailSpawn {

    startSpawn() {
        log.info("startSpawn promtail-windows-amd64.exe")
        const cmd = spawn('promtail-windows-amd64.exe', ['--config.file', './promtail-local-config.yaml'])
        cmd.stdout.on('data', function (data) {
            log.info('RtspSpawn stdout: ' + data);
        });


        cmd.stderr.on('data', function (data) {
            log.warn('RtspSpawn error: ' + data);
        });

        cmd.on('close', (code) => {
            log.error('RtspSpawn exists with code: ' + code);
            setTimeout(() => {
                this.init();
            }, 1000 * 60 * 10)
        });
    }

    private changeConfig() {
        log.info("修改promtail-local-config.yaml");
        // 配置你想要替换的值
        const replacements = {
            'DEVICE_NAME': settings.deviceName,
            'LOKI_HOST': settings.lokiHost,
        };

        // 读取YAML配置文件
        let configFileContent = fs.readFileSync('promtail-local-config-template.yaml', {encoding: 'utf8'});

        // 替换占位符
        Object.entries(replacements).forEach(([placeholder, value]) => {
            configFileContent = configFileContent.replace(new RegExp(placeholder, 'g'), value);
        });

        // 将修改后的内容写回文件
        fs.writeFileSync('promtail-local-config.yaml', configFileContent, {encoding: 'utf8'});

        console.log('配置文件已通过占位符更新。');
    }

    async init() {
        if (settings.lokiHost === '') {
            log.info("vmUrl空，不监控")
            return;
        }
        if (settings.lokiHost === undefined) {
            settings.lokiHost = 'loki.wechain360.com'
            log.info("lokiHost没有设置，开启默认", settings.lokiHost);
            this.changeConfig();
            await this.startSpawn();
        }
    }
}

const promailSpawn = new PromailSpawn();

export default promailSpawn;